package algorithm.sort;

import java.util.Arrays;

public class BinaryInsertSortTest1 {
    public static void main(String[] args) {
        int[] arr1 = { 4, 7, 5, 6, 1, 3, 8 };
        int[] arr2 = { 7, 6, 5, 4, 3, 2, 1 };
        int[] arr3 = { 5, 9, 3, 7, 8, 6, 1, 2, 4 };
        int[] arr4 = { 13, 2, 5, 4, 88, 76, 68, 87, 55, 88, 88, 77, 67, 99, 100, 5, 53, 52, 51, 66 };
        sort(arr1);
        sort(arr2);
        sort(arr3);
        sort(arr4);
        System.out.println(Arrays.toString(arr1));
        System.out.println(Arrays.toString(arr2));
        System.out.println(Arrays.toString(arr3));
        System.out.println(Arrays.toString(arr4));
    }

    public static void sort(int[] arr) {
        for (int i = 1; i < arr.length; i++) {// 循环遍历数组,定第2个元素开始,只有1个元素的话不用排序
            int value = arr[i];
            int low = 0;
            int mid = 0;
            int high = i - 1;
            while (low <= high) { // 2分法查找要插入的位置,终止条件是high=mid-1以后比low小.小于符号的满足条件的情况是high=low+1,mid=low,high=mid-1<low
                mid = (low + high) / 2;
                if (value > arr[mid]) { // 如果比mid大,下次查找的数组为mid的后半段
                    low = mid + 1;
                } else { // 否则下次查找的数组为mid的前半段
                    high = mid - 1;
                }
            }
            // value就应该放到low这个位置,所以把low之后的元素都向后移动一格
            for (int j = i; j > low; j--) {
                arr[j] = arr[j - 1];
            }
            arr[low] = value;
        }
    }
}
